package com.lw.leetcode.arr.b;

import java.util.Arrays;

/**
 * Created with IntelliJ IDEA.
 * arr
 * 910. 最小差值 II
 *
 * @author liw
 * @version 1.0
 * @date 2022/1/25 14:55
 */
public class SmallestRangeII {

    public static void main(String[] args) {
        SmallestRangeII test = new SmallestRangeII();

        // 3
        int[] arr = {1, 3, 6};
        int k = 3;

        // 6
//        int[] arr = {0, 10};
//        int k = 2;

        // 7
//        int[] arr = {3,4,7,0};
//        int k = 5;

        int i = test.smallestRangeII(arr, k);
        System.out.println(i);
    }

    public int smallestRangeII(int[] nums, int k) {
        int length = nums.length - 1;
        if (length < 1) {
            return 0;
        }
        Arrays.sort(nums);
        int a = nums[0] + k;
        int b = nums[length] - k;
        int min = b - a + (k << 1);
        for (int i = 0; i < length; i++) {
            int m1 = Math.min(a, nums[i + 1] - k);
            int m2 = Math.max(nums[i] + k, b);
            min = Math.min(min, m2 - m1);
        }
        return min;
    }

}
